
from __future__ import with_statement

### SQLITE DATABASE FACILITY
class LYDB(object):
    def __enter__(self):
        return self
    def __exit__(self, e_t, e_v, t_b):
        self.cleanup()
    def __init__(self, dbfilename):
        import sqlite3
        self.cx = sqlite3.connect(dbfilename)
        self.cu = self.cx.cursor()
    def cleanup(self):
        self.cx.close()
        print "--- CLEAN_UP_PRCOESS ---"
        print "Database context is safely closed."
    def commit(self, sql, verbose = False):
        try:
            self.cu.execute(sql)
            self.cx.commit()
        except Exception as e:
            if verbose:
                print e
                print sql          
    def commitWithRes(self, sql, verbose = False):
        self.commit(sql, verbose)
        try:
            res = self.cu.fetchall()
        except Exception:
            res = None
        return res

class TestDB(LYDB):
    def __init__(self, dbfilename):
        LYDB.__init__(self, dbfilename)
        sql = """ create table catalog (id integer primary key AUTOINCREMENT, name varchar(256));"""
        sql0 = """ insert into catalog(id, name) values(123, "123"); """

def testSqlite():
    a = TestDB("fuck.slqite3")
    with TestDB("fuck.slqite3") as t:
        while True: a = 1

### Berkeley Database Facility

class BerkeleyDB(object):
    """
    >>> testBDB()
    ('value0', 'v3')
    """
    def __enter__(self):
        return self
    def __exit__(self, e_t, e_v, t_b):
        self.cleanup()
    def __init__(self, file_path):
        import bsddb, os
        # We found the BekerleyDB doesn't support the "./XXX" path expression
        file_path = os.path.realpath(file_path)
        self.dbenv = bsddb.db.DBEnv()
        if "/" in file_path:
            dir_path = file_path[0:file_path.rindex("/")]
        else: dir_path = file_path[0:file_path.rindex("\\")]
        self.dbenv.open(dir_path, bsddb.db.DB_CREATE |bsddb.db.DB_INIT_CDB| bsddb.db.DB_INIT_MPOOL)
        self.db = bsddb.db.DB(self.dbenv)
        self.db.open(file_path, bsddb.db.DB_BTREE, bsddb.db.DB_CREATE, 0660)
    def __setitem__(self, _k, _v):
        self.db[_k] = _v
    def __getitem__(self, _k):
        return self.db[_k]
    def cleanup(self):
        self.db.sync()
        self.db.close()
        self.dbenv.close()

def testBDB():
    filepath = "./acm_technews/acm_technews.db" # Fail at the previous version
    #filepath = "./acm_technews.db" 
    with BerkeleyDB(filepath) as b:
        b["key0"] = "value0"
        b["adf"] = "v1"
        b["adfa"] = "v3"
    with BerkeleyDB(filepath) as b:
        return b["key0"], b["adfa"]

if __name__ == "__main__":
    import doctest
    doctest.testmod()
    
